﻿using HundSunDBQryFrmClient.Frm;
using HundSunDBQryFrmClient.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HundSunDBQryFrmClient
{
    public partial class FormMain : Form
    {
        DateTimePicker dateTimePicker_s;
        DateTimePicker dateTimePicker_e;
        ToolStripControlHost dateTimePickerHost_s;
        ToolStripControlHost dateTimePickerHost_e;
        DataTable dataTable;
        Dictionary<string, string> columeData = new Dictionary<string, string> {
            {"POSITION_STR","ID"},
            {"BRANCH_NAME","营业部"},
            {"BANK_NAME","银行"},
            {"BUSINESS_NAME","业务名称"},
            {"OCCUR_BALANCE","发生金额"},
            {"CURR_DATE","日期"},
            {"CURR_TIME","时间"},
            {"INIT_DATE","交易日"},
        };
        string saveName = "";
        public FormMain()
        {
            InitializeComponent();
            InitializeToolStrip();

            // 创建数据表
            dataTable = new DataTable("MyTable");

            // 设置 DataGridView 的数据源为数据表
            dataGridView1.DataSource = dataTable;
            dataGridView1.ReadOnly = true;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView1.RowHeadersVisible = true;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 在数据绑定之前或数据源发生变化时，更新行标题的值
            dataGridView1.CellFormatting += DataGridView1_CellFormatting; ;
        }

        private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var dgv = (DataGridView)sender;
                // 将行标题的值设置为行索引加一（即序号）
                if (dgv.Rows[e.RowIndex].HeaderCell.Value == null || dgv.Rows[e.RowIndex].HeaderCell.Value.ToString() != (e.RowIndex + 1).ToString())
                {
                    dgv.Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString();
                }
            }
        }

        private void InitializeToolStrip()
        {
            var button_cxdr = new ToolStripButton("查询当日");
            button_cxdr.Click += Button_cxdr_Click;
            toolStrip1.Items.Add(button_cxdr);
            toolStrip1.Items.Add(new ToolStripSeparator());
            // 添加日期标签
            ToolStripLabel dateLabel = new ToolStripLabel("选择日期");
            toolStrip1.Items.Add(dateLabel);
            dateTimePicker_s = new DateTimePicker();
            dateTimePicker_s.Format = DateTimePickerFormat.Short;
            dateTimePickerHost_s = new ToolStripControlHost(dateTimePicker_s);
            dateTimePicker_e = new DateTimePicker();
            dateTimePicker_e.Format = DateTimePickerFormat.Short;
            dateTimePickerHost_e = new ToolStripControlHost(dateTimePicker_e);
            toolStrip1.Items.Add(dateTimePickerHost_s);
            toolStrip1.Items.Add(new ToolStripLabel("->"));
            toolStrip1.Items.Add(dateTimePickerHost_e);
            var button_cxls = new ToolStripButton("查询历史");
            button_cxls.Click += Button_cxls_Click;
            toolStrip1.Items.Add(button_cxls);
            toolStrip1.Items.Add(new ToolStripSeparator());
            var button_dryy = new ToolStripButton("导出数据");
            button_dryy.Click += Button_dryy_Click;
            toolStrip1.Items.Add(button_dryy);
            
        }
        private void SetStatusMsg(string message) 
        {
            this.Invoke(new Action(() =>
            {
                toolStripStatusLabel1.Text = message;
            }));
            
        }

        private void Button_dryy_Click(object sender, EventArgs e)
        {
            string path = ConfigurationManager.AppSettings.Get("SavePath");
            if (path!=null)
            {
                // 检查路径是否存在，如果不存在则创建
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    Console.WriteLine("路径已创建成功！");
                }
                var filepath=Path.Combine(path, saveName + ".xlsx");
                ExcelHelp.writeExcel(dataTable, filepath);
                MessageBox.Show("OK");
            }
            else
            {
                MessageBox.Show($"配置SavePath不存在");
            }

            //ExcelHelp.Export(dataTable,saveName);
        }

        private void Button_cxls_Click(object sender, EventArgs e)
        {
            SetStatusMsg("查询中...");
            string url = new Uri(new Uri(ConfigurationManager.AppSettings["ServerBaseUrl"]), "/api/QrySqlStr").ToString();
            var webrsp = HundsunDB.getData(url, $"select t.position_str,t.init_date,t.curr_date,t.curr_time,t.branch_no,t.business_flag,t.bank_no,t.occur_balance,y.bank_name,u.branch_name,i.business_name,t.remark from (select  t.* from hs_his.his_fundjour t where t.init_date>='{dateTimePicker_s.Value.ToString("yyyyMMdd")}' and t.init_date<='{dateTimePicker_e.Value.ToString("yyyyMMdd")}' and t.bank_no!='0' and (t.business_flag='2041' or t.business_flag='2042' or t.business_flag='2141' or t.business_flag='2142') ) t,HS_ASSET.BANKARG y,hs_user.allbranch u,hs_user.businflag i where t.bank_no=y.bank_no and t.branch_no=u.branch_no and t.business_flag=i.business_flag");
            List<Dictionary<string, string>> data = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(JsonConvert.SerializeObject(webrsp.data));
            ShowData(data);
            SetStatusMsg("查询完成");
            MessageBox.Show("查询完成");
        }

        private void Button_cxdr_Click(object sender, EventArgs e)
        {
            SetStatusMsg("查询中...");
            string url = new Uri(new Uri(ConfigurationManager.AppSettings["ServerBaseUrl"]), "/api/QrySqlStr").ToString();
            var webrsp = HundsunDB.getData(url, "select t.position_str,t.init_date,t.curr_date,t.curr_time,t.branch_no,t.business_flag,t.bank_no,t.occur_balance,y.bank_name,u.branch_name,i.business_name,t.remark from (select  t.* from HS_ASSET.FUNDJOUR t where t.bank_no!='0' and (t.business_flag='2041' or t.business_flag='2042' or t.business_flag='2141' or t.business_flag='2142') ) t,HS_ASSET.BANKARG y,hs_user.allbranch u,hs_user.businflag i where t.bank_no=y.bank_no and t.branch_no=u.branch_no and t.business_flag=i.business_flag");
            List<Dictionary<string, string>> data=JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(JsonConvert.SerializeObject(webrsp.data));
            ShowData(data);
            SetStatusMsg("查询完成");
            MessageBox.Show("查询完成");
        }

        private void ShowData(List<Dictionary<string, string>> data) 
        {
            string qryStartDate = "";
            string qryEndDate = "";
            dataTable.Rows.Clear();
            dataTable.Columns.Clear();
            if (data.Count > 0)
            {
                foreach (var cd in columeData)
                {
                    foreach (var item in data[0])
                    {
                        if (item.Key == cd.Key)
                        {
                            dataTable.Columns.Add(cd.Value);
                            break;
                        }
                    }
                }
            }
            
            foreach (var item in data)
            {
                List<object> rows= new List<object>();
                foreach (var cd in columeData)
                {
                    if (item.ContainsKey(cd.Key))
                    {
                        rows.Add(item[cd.Key]);
                        if (cd.Key== "INIT_DATE")
                        {
                            if (qryStartDate=="")
                            {
                                qryStartDate = item[cd.Key];
                            }
                            else if(int.Parse(qryStartDate)>int.Parse(item[cd.Key]))
                            {
                                qryStartDate = item[cd.Key];
                            }
                            if (qryEndDate == "")
                            {
                                qryEndDate = item[cd.Key];
                            }
                            else if (int.Parse(qryEndDate) < int.Parse(item[cd.Key]))
                            {
                                qryEndDate = item[cd.Key];
                            }
                        }
                    }
                }
                dataTable.Rows.Add(rows.ToArray());
            }
            if (!string.IsNullOrEmpty(qryStartDate)&&!string.IsNullOrEmpty(qryEndDate))
            {
                if (qryStartDate==qryEndDate)
                {
                    saveName = qryEndDate;
                }
                else
                {
                    saveName = qryStartDate+"-"+qryEndDate;
                }
            }
        }

        private void 修改密码ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var webrsp = FormChangePassword.show();
            if (webrsp != null&&webrsp.code==0) 
            {
                MessageBox.Show("修改成功");
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            SetStatusMsg("就绪");
        }

        private void 查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string url = new Uri(new Uri(ConfigurationManager.AppSettings["ServerBaseUrl"]), "/api/QrySqlStr").ToString();
            var webrsp = HundsunDB.getData(url, "select * from hs_user.businflag t where t.business_flag='2041' or t.business_flag='2042' or t.business_flag='2141' or t.business_flag='2142'");

        }

    }
}
